<?php
/**
 * Created by PhpStorm
 * User: Jhinwy
 * Date: 5/21/24
 * Time: 1:53 PM
 */

namespace App\Http\Middleware;

use Closure;

class CrossHttp
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */

    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $response = $next($request);

        // 处理预检请求
        if ($request->getMethod() === 'OPTIONS') {

            return response('', 200);
        }

        // 允许所有资源跨域
        $response->header('Access-Control-Allow-Origin', '*');
        // 允许通过的响应报头
        $response->header('Access-Control-Allow-Headers', 'Origin, Content-Type, Cookie, Accept, Authorization, application/json, X-Auth-Token, Referer,User-Agent');
        // 允许的请求方法
        $response->header('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, OPTIONS, DELETE');
        // 允许axios获取响应头中的Authorization
        $response->header('Access-Control-Expose-Headers', 'Authorization');
        // 允许的请求方法
        $response->header('Allow', 'GET, POST, PATCH, PUT, OPTIONS, DELETE');
        // 允许客户端携带证书式访问
        $response->header('Access-Control-Allow-Credentials', 'true');

        return $response;
    }

}
